/**********************************************************************
 Copyright (C) 2009 Jaakko Vuori

 This file is part of FlexiWorker.
 For more information, see <http://code.google.com/p/flexi-worker/>

 FlexiWorker is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 FlexiWorker is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with FlexiWorker.  If not, see <http://www.gnu.org/licenses/>.
 **********************************************************************/

#include "idlemonitor.h"

#ifdef Q_OS_LINUX
#include "idlemonitor_linux_p.h"
#endif
#ifdef Q_OS_WIN
#include "idlemonitor_win_p.h"
#endif

#include <QTimer>

const unsigned int IdleTriggerTime = 15 * 60000;
const unsigned int activePollingInterval = 60000;
const unsigned int idlePollingInterval = 1000;

IdleMonitor::IdleMonitor(QObject* parent) : QObject(parent),
    m_d(new IdleMonitorPrivate),
    m_state(Active)
{
    m_timer = new QTimer(this);
    connect(m_timer, SIGNAL(timeout()), this, SLOT(checkIdleTime()));
    m_timer->start(activePollingInterval);
}

IdleMonitor::~IdleMonitor()
{
    delete m_d;
}

void IdleMonitor::checkIdleTime()
{
    unsigned int idleTime = m_d->idleTimeInMilliSeconds();

    if (m_state == Active && idleTime > IdleTriggerTime)
    {
        m_timer->setInterval(idlePollingInterval);
        m_state = Idle;
        QDateTime lastActivityTime = QDateTime::currentDateTime().addMSecs(-qint64(idleTime));
        emit idle(lastActivityTime);
    }
    if (m_state == Idle && idleTime < IdleTriggerTime)
    {
        m_timer->setInterval(activePollingInterval);
        m_state = Active;
        emit back();
    }
}
